<template>
	<view>
		<block v-if="ptype">
			<!-- <view class="" @click="uploadImg">图片</view>
			<view class="" @click="uploadVideo">视频</view>
			<view class="" @click="uploadText">文案</view> -->
			<view class="top">
				<view class="top_l">发布类型：</view>
				<view class="top_l" @click="selectType">
					<block v-if="ptype==3">图片</block>
					<block v-else-if="ptype==1">视频</block>
					<block v-else>文案</block>
				</view>
				<image src="/static/issueMore.png" class="top_r" @click="selectType"></image>
			</view>
			<!-- 
			<view class="top" style="margin-top: 20rpx;">
				<view class="top_l">选择专题：</view>
				<view class="top_l" @click="selectSubject">{{subjectText}}</view>
				<image src="/static/issueMore.png" class="top_r" @click="selectType"></image>
			</view>
			
			<view class="top" style="margin-top: 20rpx;">
				<view class="top_l">选择分类：</view>
				<view class="top_l" @click="selectType">
					<block v-if="ptype==0">图片</block>
					<block v-else-if="ptype==1">视频</block>
					<block v-else>文案</block>
				</view>
				<image src="/static/issueMore.png" class="top_r" @click="selectType"></image>
			</view> -->
			
			<!-- 图片 -->
			<view class="img" v-if="ptype==3">
				<view class="img_title">选择图片 <text>最多可选择9张图片</text></view>
				<view class="image">
					<block v-for="(item,index) in imgurl" :key="index">
						<view class="imagebox">
							<image src="/static/imgDelete.png" class="imagebox_delete" @click="deleteImg(index)"></image>
							<image :src="item" class="imagebox_img" mode="aspectFill" @click="previewImage(index)" ></image>
						</view>
					</block>
					<view class="image_boxes" @click="selectImg" v-if="imgNum<=8">
						<image src="/static/selectImg.png" class="image_boxes_image"></image>
					</view>
				</view>
			</view>
			
			<!-- 视频 -->
			<view class="video" v-if="ptype==1">
				<view class="video_l">
					<view class="video_l_t">选择视频</view>
					<textarea class="video_l_input" placeholder="请输入您的视频描述" placeholder-class="placeholder" :value="title" @input="inputTitle"></textarea>
				</view>
				<view class="video_r">
					<block v-if="videoUrl">
						<view class="video_r_box" @click="deleteVideo"><image src="/static/materialDelete.png" class="video_r_box_img"></image></view>
						<video :src="videoUrl" id="myVideo" @play='videoPlay(videoUrl)' @fullscreenchange="fullscreenchange" class="video_r_video" object-fit="cover"></video>
					</block>
					<block v-else>
						<image src="/static/selectImg.png" class="video_r_img" @click="uploadVideo"></image>
					</block>
				</view>
			</view>
			
			<!-- 文案 -->
			<view class="text" v-if="ptype==2">
				<view class="text_title">输入文案</view>
				<textarea :value="text" @input="inputText" placeholder="请输入您的文案" placeholder-class="placeholder" class="text_input" />
			</view>
			
			<!-- 提交 -->
			<block v-if="showButton==true">
				<view class="submit" v-if="ptype==3" @click="submitImg">提交审核</view>
				<view class="submit" v-else-if="ptype==1" @click="submitVideo">提交审核</view>
				<view class="submit" @click="submitText" v-else>提交审核</view>
			</block>
			<!-- <block v-else>
				<view class="submit">提交审核</view>
			</block> -->
		</block>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				config : {
				    qiniuRegion: '',
				    qiniuBucketURLPrefix: '',
					url: '',
				    qiniuUploadToken: '',
				    qiniuUploadTokenURL: '',
				    qiniuUploadTokenFunction: function () { },
				    qiniuShouldUseQiniuFileName: false,
					name: '',
					token: '',
				},
				ptype: null,
				zoneid: '',
				url: '',
				ctypeid: '',
				title: '',
				text: '',
				imgurl: '',
				imgNum: 0,
				imgIndex: 0,
				videoUrl: '',
				subjectList: '',
				subjectText: '',
				playId: '',
				showButton: true,
				tabList: [],
				videoContext: '',
			};
		},
		
		onLoad() {
			let that = this
			// 选择类型
			uni.request({
				url: getApp().globalData.url + '/fp/ptypelist',
				method: 'POST',
				success(res) {
					let list = []
					for(var i=0;i<res.data.data.length;i++){
						list.push(res.data.data[i].ptypename)
					}
					that.tabList = list
					that.ptype = res.data.data[0].ptype
				}
			})
		},
		
		onShow() {
			let that = this
			
			// 资源类型
			// uni.request({
			// 	url: getApp().globalData.url + '/fp/ctypelist',
			// 	method: 'POST',
			// 	header: {
			// 		token: uni.getStorageSync('token')
			// 	},
			// 	success(res) {
			// 		if(res.data.code==20000){
			// 			that.subjectList = res.data.data
			// 		}
			// 	}
			// })
			
			
			
			// 专题
			uni.request({
				url: getApp().globalData.url + '/fp/zonelist',
				method: 'POST',
				success(res) {
					that.subjectcList = res.data.data
					
				}
			})
			
			uni.request({
				url: getApp().globalData.url + '/pub/getbuckettoken',
				method: 'POST',
				success(res1) {
					that.config.qiniuUploadToken = res1.data.token
					that.config.url = res1.data.qiniuhostname
					that.config.name = res1.qiniuhostname
					that.config.token = res1.token  
				}
			})
		},
		
		methods: {
			// 选择类型
			selectType(){
				let that = this
				
				uni.showActionSheet({
					itemList: that.tabList,
					success: function (res) {
						// if(that.ptype == res.tapIndex){
						// 	return false
						// }
						// that.ptype = res.tapIndex
						
						switch(that.tabList[res.tapIndex]){
							case '图片':
								that.ptype = 3
								break;
						    case '视频':
								that.ptype = 1
								break;
							case '文案':
								that.ptype = 2
								break;
						}
						console.log(that.ptype)
					}
				})
			},
			
			// 选择专题
			selectSubject(){
				let that = this
				
				uni.showActionSheet({
					itemList: that.subjectList,
					success: function (res) {
						that.subjectText = that.subjectList[res.tapIndex].zonename
					}
				})
			},
			
			// 选择图片
			selectImg(){
				let that = this
				
				let imgNum = 9 - that.imgNum
				uni.chooseImage({
					count: imgNum,
					success(res) {
						if(that.imgurl){
							that.imgurl = that.imgurl.concat(res.tempFilePaths)
						}else{
							that.imgurl = res.tempFilePaths
						}
						that.imgNum = that.imgurl.length
					}
				})
			},
			
			// 删除照片
			deleteImg(i){
				let that = this
				
				let imgurl = that.imgurl
				
				imgurl.splice(i,1)
				that.imgurl = imgurl
				that.imgNum = that.imgNum - 1
			},
			
			// 预览图片
			previewImage(index){
				let that = this
				
				uni.previewImage({
					urls: that.imgurl,
					current: index
				});
			},
			
			// 提交图片
			submitImg(){
				let that = this
				
				if(that.showButton){
					that.showButton = false
					const imgurl = that.imgurl.map((item,index)=>{
						uni.compressImage({
							src: item,
							quality: 60,
							success: res => {
								const tempFilePaths = res.tempFilePath
								that.uploadFile(tempFilePaths)
							}
						})
					})
				}
			},
			
			
			compressImage() {
				let that = this
				const imgurl = that.imgurl.map((item,index)=>{
					uni.compressImage({
						src: item,
						quality: 60,
						success: res => {
							const tempFilePaths = res.tempFilePath
							that.uploadFile(tempFilePaths)
						}
					})
				})
			},
			
			// 全屏播放
			// videoPlay(url){
			// 	let videoContext = uni.createVideoContext('myVideo')
			// 	// videoContext.pause()
			// 	videoContext.requestFullScreen()
			// },
			
			// 视频播放
			videoPlay(id) {
				let that = this
				
				that.videoContext = uni.createVideoContext(`myVideo`)
				that.videoContext.requestFullScreen()
			},
			
			// 进入/退出全屏
			fullscreenchange(e){
				let that = this
				
				if(!e.detail.fullScreen){
					that.videoContext.pause()
				}
			},
			
			
			// 删除视频
			deleteVideo(){
				let that = this
				
				that.videoUrl = ''
			},
			
			// 提交视频
			submitVideo(){
				let that = this
				
				if(that.showButton){
					console.log(that.showButton)
					that.showButton = false
					console.log(that.showButton)
					if(that.videoUrl){
						if(that.title){
							that.request()
						}else{
							that.showButton = true
							uni.showToast({
								title: '请输入视频描述',
								icon: 'none'
							})
						}
					}else{
						that.showButton = true
						uni.showToast({
							title: '请上传视频',
							icon: 'none'
						})
					}
				}
			},
			
			// 视频描述
			inputTitle(e){
				let that = this
				
				that.title = e.detail.value
			},
			
			// 视频
			uploadVideo() {
				let that = this
				return new Promise((resolve, reject) => {
					that.chooseVideo().then(tempFilePaths => {
						that.uploadFile(tempFilePaths).then(res => {
							resolve(res);
						}).catch(err => {
							reject(err);
						})
					})
				})
			},
			
			chooseVideo() {
				let that = this
				return new Promise((resolve, reject) => {
					uni.chooseVideo({
						success(file) {
							const tempFilePaths = file.tempFilePath
							that.videoUrl = tempFilePaths
							resolve(tempFilePaths);
							// uni.compressVideo({
							// 	src: file.tempFilePath,
							// 	// quality: 'medium',
							// 	success: (res) => {
							// 		console.log(res,'res-----======')
							// 		const tempFilePaths = res.tempFilePath
							// 		that.videoUrl = tempFilePaths
							// 		resolve(tempFilePaths);
							// 	},
							// 	fail: (err) => {
							// 		console.log(err,'err=================')
							// 	},
							// })
						},
						fail(err) {
							wx.hideLoading()
							reject(err);
						}
					})
				});
			},
			
			inputText(e){
				let that = this
				
				that.text = e.detail.value
			},
			
			// 文案
			submitText(){
				let that = this
				console.log(that.showButton)
				if(that.showButton){
					that.showButton = false
					console.log(that.showButton)
					if(that.text){
						that.request()
					}else{
						uni.showToast({
							title: '请输入您的文案',
							icon: 'none'
						})
					}
				}
			},
			
			request(){
				let that = this
				
				console.log(123)
				that.showButton = false
				uni.request({
					url: getApp().globalData.url + '/fp/upload',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						token: uni.getStorageSync('token')
					},
					data: {
						openid: uni.getStorageSync('openid'),
						ptype: that.ptype == 3 ? '0' : that.ptype,
						zoneid: that.zoneid,
						ctypeid: that.ctypeid,
						url: that.url,
						title: that.ptype == 1 ? that.title : '',
						word: that.text
					},
					success(res) {
						if(res.data.code==20000){
							if(that.ptype == 0){
								that.imgIndex = that.imgIndex + 1
								if(that.imgIndex == that.imgNum){
									uni.showToast({
										title: res.data.msg,
										success() {
											setTimeout(()=>{
												uni.navigateBack()
											},1500)
										}
									})
								}
							}else{
								uni.showToast({
									title: res.data.msg,
									success() {
										setTimeout(()=>{
											uni.navigateBack()
										},1500)
									}
								})
							}
						}else{
							that.showButton = true
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
						
					}
				})
			},
			
			uploadFile(path) {
			let that = this
			
				return new Promise((resolve, reject) => {
					// wx.showLoading()
					// uni.request({
					// 	url: getApp().globalData.url + '/pub/getbuckettoken',
					// 	method: 'POST',
					// 	success(res1) {
					// 		that.config.qiniuUploadToken = res1.data.token
					// 		that.config.url = res1.data.qiniuhostname
							that.upload(path, (res) => {
								console.log(1234)
								wx.hideLoading()
								resolve(res.imageURL)
							}, (error) => {
								wx.hideLoading()
							}, {
								region: 'SCN', //华南
								// domain: res1.qiniuhostname, // 
								domain: that.config.name, // 
								key: 'st/'+new Date().getFullYear()+"/"+(new Date().getMonth()+1)+"/"
								+new Date().getDate()+"/"+new Date().getTime() + "_" + Math.random().toFixed(6).slice(-
									6) + ".jpg",
								// uptoken: res1.token,
								uptoken: that.config.token,
							});
					// 	}
					// })
				});
			},
			
			
			// init(options) 将七牛云相关配置初始化进本sdk
			// 在整个程序生命周期中，只需要 init(options); 一次即可
			// 如果需要变更七牛云配置，再次调用 init(options); 即可
			init(options) {
				let that = this
				that.updateConfigWithOptions(options);
			},
		
			// 更新七牛云配置
			updateConfigWithOptions(options) {
				let that = this
				if (options.region) {
					that.config.qiniuRegion = options.region;
				} else {
					console.error('qiniu uploader need your bucket region');
				}
				if (options.uptoken) {
					that.config.qiniuUploadToken = options.uptoken;
				} else if (options.uptokenURL) {
					that.config.qiniuUploadTokenURL = options.uptokenURL;
				} else if (options.uptokenFunc) {
					that.config.qiniuUploadTokenFunction = options.uptokenFunc;
				}
				if (options.domain) {
					that.config.qiniuBucketURLPrefix = options.domain;
				}
					that.config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
			},
		
			// 正式上传的前置方法，做预处理，应用七牛云配置
			upload(filePath, success, fail, options, progress, cancelTask) {
				let that = this
				// console.log(that.config,'that.config')
				if (null == filePath) {
					console.error('qiniu uploader need filePath to upload');
					return;
				}
				if (options) {
					that.updateConfigWithOptions(options);
				}
				if (that.config.qiniuUploadToken) {
					that.doUpload(filePath, success, fail, options, progress, cancelTask);
				} else if (that.config.qiniuUploadTokenURL) {
					that.getQiniuToken(function () {
						that.doUpload(filePath, success, fail, options, progress, cancelTask);
					});
				} else if (that.config.qiniuUploadTokenFunction) {
					that.config.qiniuUploadToken = that.config.qiniuUploadTokenFunction();
					// console.log(that.config.qiniuUploadTokenFunction)
					if (that.config.qiniuUploadToken && that.config.qiniuUploadToken.length > 0) {
						console.error('qiniu UploadTokenFunction result is null, please check the return value');
						return
					}
					that.doUpload(filePath, success, fail, options, progress, cancelTask);
				} else {
					console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
					return;
				}
			},
		
			// 正式上传
			doUpload(filePath, success, fail, options, progress, cancelTask) {
				let that = this
				
				console.log(213544)
				if (null == that.config.qiniuUploadToken && that.config.qiniuUploadToken.length > 0) {
					console.error('qiniu UploadToken is null, please check the init config or networking');
					return
				}
				// console.log(that.config,'---------------------------')
				var url = that.uploadURLFromRegionCode(that.config.qiniuRegion);
				var fileName = filePath.split('//')[1];
				// 自定义上传key（即自定义上传文件名）。通过修改qiniuUploader.upload方法传入的options参数，可以进行自定义文件名称。如果options非空，则使用options中的key作为fileName
				if (options && options.key) {
					fileName = options.key;
				}
				var formData = {
					'token': that.config.qiniuUploadToken
				};
				// qiniuShouldUseQiniuFileName 如果是 true，则文件的 key 由 qiniu 服务器分配（全局去重）。如果是 false，则文件的 key 使用微信自动生成的 filename。出于初代sdk用户升级后兼容问题的考虑，默认是 false。
				if (!that.config.qiniuShouldUseQiniuFileName) {
					formData['key'] = fileName
				}
				var uploadTask = wx.uploadFile({
					url: url,
					filePath: filePath,
					name: 'file',
					formData: formData,
					success: function (res) {
						var dataString = res.data
						//   // that if case is a compatibility with wechat server returned a charcode, but was fixed
						//   if(res.data.hasOwnProperty('type') && res.data.type === 'Buffer'){
						//     dataString = String.fromCharCode.apply(null, res.data.data)
						//   }
						try {
							var dataObject = JSON.parse(dataString);
							// 拼接fileURL
							var fileURL = that.config.qiniuBucketURLPrefix + '/' + dataObject.key;
							dataObject.fileURL = fileURL;
							// imageURL字段和fileURL字段重复，但本sdk不做删除，因为在最初版本使用的是imageURL。直接删除可能导致原有用户升级至新版sdk后出现异常。
							dataObject.imageURL = fileURL;
							if (success) {
								that.url = that.config.url + '/' + dataObject.key
								// console.log(that.url)
								if(that.ptype == 3){
									that.request()
									success(dataObject);
								}
									// that.request()
									// success(dataObject);
							}
						} catch (e) {
							console.log('parse JSON failed, origin String is: ' + dataString)
							if (fail) {
								fail(e);
							}
						}
					},
					fail: function (error) {
						console.error(error);
						if (fail) {
							fail(error);
						}
					}
				})
		
				// 文件上传进度
				uploadTask.onProgressUpdate((res) => {
					progress && progress(res)
				})
		
				// 中断文件上传
				cancelTask && cancelTask(() => {
					uploadTask.abort()
				})
			},
		
			// 获取七牛云uptoken, url为后端服务器获取七牛云uptoken接口
			getQiniuToken(callback) {
				let that = this
				wx.request({
					url: that.config.qiniuUploadTokenURL,
					success: function (res) {
						var token = res.data.uptoken;
						console.log(token)
						if (token && token.length > 0) {
							that.config.qiniuUploadToken = token;
							if (callback) {
								callback();
							}
						} else {
							console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
						}
					},
					fail: function (error) {
						console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
					}
				})
			},
		
			// 选择七牛云文件上传接口，文件向匹配的接口中传输。ECN, SCN, NCN, NA, ASG，分别对应七牛云的：华东，华南，华北，北美，新加坡 5 个区域
			uploadURLFromRegionCode(code) {
				var uploadURL = null;
				switch (code) {
					case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
					case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
					case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
					case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
					case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
					default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
				}
				return uploadURL;
			},
		}
	}
</script>

<style lang="scss">
	page{
		background: #ECECEC;
	}
	
	.top{
		width: 750rpx;
		height: 128rpx;
		background: #FFFFFF;
		
		&_l{
			float: left;
			margin: 49rpx 0rpx 49rpx 30rpx;
			height: 30rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #000000;
			line-height: 30rpx;
		}
		&_r{
			float: left;
			padding: 55rpx 30rpx 54rpx 390rpx;
			// padding-left: 390rpx;
			width: 34rpx;
			height: 20rpx;
		}
	}
	
	// 图片
	.img{
		margin-top: 20rpx;
		width: 750rpx;
		background: #FFFFFF;
		overflow: hidden;
		
		&_title{
			margin: 40rpx 32rpx;
			height: 30rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #000000;
			line-height: 30rpx;
			
			text{
				margin-left: 20rpx;
				font-size: 24rpx;
				color: #C4C4C4;
			}
		}
		.image{
			margin-left: 40rpx;
			margin-bottom: 16rpx;
			overflow: hidden;
			
			&_boxes{
				float: left;
				margin-right: 24rpx;
				margin-bottom: 24rpx;
				width: 208rpx;
				height: 208rpx;
				border: 1rpx solid #E0E0E0;
				border-radius: 12rpx;
				// box-sizing: border-box;
				overflow: hidden;
				
				&_image{
					margin: 31rpx;
					width: 146rpx;
					height: 146rpx;
				}
			}
			.imagebox{
				position: relative;
				float: left;
				margin-right: 24rpx;
				margin-bottom: 24rpx;
				width: 208rpx;
				height: 208rpx;
				overflow: hidden;
				
				&_img{
					width: 208rpx;
					height: 208rpx;
				}
				&_delete{
					position: absolute;
					top: 9rpx;
					right: 9rpx;
					width: 42rpx;
					height: 42rpx;
					z-index: 2;
				}
			}
		}
	}
	
	// 视频
	.video{
		padding-bottom: 20rpx;
		margin-top: 20rpx;
		width: 750rpx;
		// height: 267rpx;
		background: #FFFFFF;
		overflow: hidden;
		
		&_l{
			// float: left;
			margin-top: 40rpx;
			margin-left: 32rpx;
			width: 600rpx;
			height: 200rpx;
			overflow: hidden;
			
			&_t{
				height: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #000000;
				line-height: 30rpx;
			}
			&_input{
				margin: 20rpx 0;
				width: 600rpx;
				height: 150rpx;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #000000;
				line-height: 30rpx;
				overflow: hidden;
			}
			.placeholder{
				font-weight: 400;
				font-size: 28rpx;
				color: #C4C4C4;
			}
		}
		&_r{
			position: relative;
			// float: right;
			margin-top: 30rpx;
			margin-left: 30rpx;
			width: 208rpx;
			height: 208rpx;
			border: 1px solid #E0E0E0;
			overflow: hidden;
			
			&_img{
				margin: 31rpx;
				width: 146rpx;
				height: 146rpx;
			}
			&_box{
				position: absolute;
				bottom: 0rpx;
				left: 0rpx;
				width: 208rpx;
				height: 56rpx;
				background: rgba(0, 0, 0, 0.6);
				overflow: hidden;
				z-index: 99;
				
				&_img{
					margin-top: 11rpx;
					margin-left: 87rpx;
					width: 34rpx;
					height: 36rpx;
				}
			}
			&_video{
				width: 208rpx;
				height: 208rpx;
			}
		}
	}
	
	// 文案
	.text{
		margin-top: 20rpx;
		width: 750rpx;
		height: 400rpx;
		background: #FFFFFF;
		overflow: hidden;
		
		&_title{
			margin-top: 40rpx;
			margin-left: 30rpx;
			height: 30rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #000000;
			line-height: 30rpx;
		}
		&_input{
			margin-top: 20rpx;
			margin-left: 30rpx;
			width: 660rpx;
			height: 300rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #000000;
			line-height: 67rpx;
			overflow: hidden;
		}
		.placeholder{
			font-weight: 400;
			font-size: 28rpx;
			color: #C4C4C4;
		}
	}
	
	// 提交
	.submit{
		position: fixed;
		bottom: 0rpx;
		left: 0rpx;
		width: 750rpx;
		height: 120rpx;
		text-align: center;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 36rpx;
		color: #FFFFFF;
		letter-spacing: 3px;
		line-height: 100rpx;
		background: #03AEA5;
		overflow: hidden;
		z-index: 1;
	}
</style>
